package com.wusiwei.controller;

import com.wusiwei.common.Result;
import com.wusiwei.entity.Order;
import com.wusiwei.service.OrderService;
import com.wusiwei.vo.OrderStatistics;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 订单控制器
 */
@RestController
@RequestMapping("/api/orders")
@RequiredArgsConstructor
@Slf4j
@Tag(name = "订单管理", description = "订单管理相关的API接口")
public class OrderController {

    private final OrderService orderService;

    /**
     * 根据ID获取订单
     *
     * @param id 订单ID
     * @return 订单信息
     */
    @GetMapping("/{id}")
    @Operation(summary = "获取订单详情", description = "根据ID获取订单的详细信息")
    public Result<Order> getOrderById(@Parameter(description = "订单ID") @PathVariable Long id) {
        try {
            log.info("获取订单详情, ID: {}", id);
            Order order = orderService.getOrderById(id);
            if (order != null) {
                return Result.success(order);
            } else {
                return Result.error("订单不存在");
            }
        } catch (Exception e) {
            log.error("获取订单详情失败, ID: {}", id, e);
            return Result.error("获取订单详情失败: " + e.getMessage());
        }
    }

    /**
     * 创建订单
     *
     * @param order 订单信息
     * @return 创建的订单
     */
    @PostMapping
    @Operation(summary = "创建订单", description = "创建新的订单记录")
    public Result<Order> createOrder(@RequestBody Order order) {
        try {
            boolean success = orderService.createOrder(order);
            if (success) {
                // 根据订单号重新查询订单信息
                Order createdOrder = orderService.getOrderById(order.getId());
                return Result.success(createdOrder);
            } else {
                return Result.error("创建订单失败");
            }
        } catch (Exception e) {
            log.error("创建订单失败", e);
            return Result.error("创建订单失败: " + e.getMessage());
        }
    }

    /**
     * 更新订单
     *
     * @param id    订单ID
     * @param order 更新的订单信息
     * @return 更新后的订单
     */
    @PutMapping("/{id}")
    @Operation(summary = "更新订单", description = "根据ID更新订单信息")
    public Result<Order> updateOrder(@Parameter(description = "订单ID") @PathVariable Long id, @RequestBody Order order) {
        try {
            boolean success = orderService.updateOrder(id, order);
            if (success) {
                // 重新获取更新后的订单
                Order updatedOrder = orderService.getOrderById(id);
                return Result.success(updatedOrder);
            } else {
                return Result.error("订单不存在或更新失败");
            }
        } catch (Exception e) {
            log.error("更新订单失败, ID: {}", id, e);
            return Result.error("更新订单失败: " + e.getMessage());
        }
    }

    /**
     * 删除订单
     *
     * @param id 订单ID
     * @return 操作结果
     */
    @DeleteMapping("/{id}")
    @Operation(summary = "删除订单", description = "根据ID删除订单")
    public Result<Void> deleteOrder(@Parameter(description = "订单ID") @PathVariable Long id) {
        try {
            boolean success = orderService.deleteOrder(id);
            if (success) {
                return Result.success();
            } else {
                return Result.error("订单不存在或删除失败");
            }
        } catch (Exception e) {
            log.error("删除订单失败, ID: {}", id, e);
            return Result.error("删除订单失败: " + e.getMessage());
        }
    }

    /**
     * 批量删除订单
     *
     * @param ids 订单ID列表
     * @return 操作结果
     */
    @DeleteMapping("/batch")
    @Operation(summary = "批量删除订单", description = "批量删除多个订单")
    public Result<Void> batchDeleteOrder(@Parameter(description = "订单ID列表") @RequestBody List<Long> ids) {
        try {
            boolean success = orderService.batchDeleteOrders(ids);
            if (success) {
                return Result.success();
            } else {
                return Result.error("部分或全部订单删除失败");
            }
        } catch (Exception e) {
            log.error("批量删除订单失败, IDs: {}", ids, e);
            return Result.error("批量删除订单失败: " + e.getMessage());
        }
    }

    /**
     * 分页查询订单
     *
     * @param pageNum      页码
     * @param pageSize     每页大小
     * @param orderNumber  订单号
     * @param supplierName 供应商
     * @param status       状态
     * @param startDate    开始日期
     * @param endDate      结束日期
     * @return 订单分页结果
     */
    @GetMapping("/page")
    @Operation(summary = "分页查询订单", description = "根据条件分页查询订单")
    public Result<Object> getOrderPage(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") int pageNum,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") int pageSize,
            @Parameter(description = "订单号") @RequestParam(required = false) String orderNumber,
            @Parameter(description = "供应商名称") @RequestParam(required = false) String supplierName,
            @Parameter(description = "订单状态") @RequestParam(required = false) String status,
            @Parameter(description = "开始日期，格式：yyyy-MM-dd") @RequestParam(required = false) String startDate,
            @Parameter(description = "结束日期，格式：yyyy-MM-dd") @RequestParam(required = false) String endDate) {
        try {
            Object result = orderService.getOrderPage(pageNum, pageSize, orderNumber, supplierName, status, startDate, endDate);
            return Result.success(result);
        } catch (Exception e) {
            log.error("分页查询订单失败", e);
            return Result.error("分页查询订单失败: " + e.getMessage());
        }
    }

    /**
     * 获取订单状态统计
     *
     * @return 订单状态统计
     */
    @GetMapping("/statistics/status")
    @Operation(summary = "获取订单状态统计", description = "统计不同状态的订单数量")
    public Result<OrderStatistics> getOrderStatusStatistics() {
        try {
            OrderStatistics statistics = orderService.getOrderStatusStatistics();
            return Result.success(statistics);
        } catch (Exception e) {
            log.error("获取订单状态统计失败", e);
            return Result.error("获取订单状态统计失败: " + e.getMessage());
        }
    }

    /**
     * 导出订单
     *
     * @param orderNumber  订单号
     * @param supplierName 供应商名称
     * @param status       状态
     * @param startDate    开始日期
     * @param endDate      结束日期
     * @return 导出的文件
     */
    @GetMapping("/export")
    @Operation(summary = "导出订单", description = "将订单数据导出为Excel文件")
    public ResponseEntity<?> exportOrders(
            @Parameter(description = "订单号") @RequestParam(required = false) String orderNumber,
            @Parameter(description = "供应商名称") @RequestParam(required = false) String supplierName,
            @Parameter(description = "状态") @RequestParam(required = false) String status,
            @Parameter(description = "开始日期，格式：yyyy-MM-dd") @RequestParam(required = false) String startDate,
            @Parameter(description = "结束日期，格式：yyyy-MM-dd") @RequestParam(required = false) String endDate) {
        try {
            log.info("导出订单数据, 订单号: {}, 供应商: {}, 状态: {}, 日期范围: {} - {}",
                    orderNumber, supplierName, status, startDate, endDate);

            // 获取当前认证用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication == null || !authentication.isAuthenticated() ||
                    authentication.getPrincipal().equals("anonymousUser")) {
                log.warn("导出订单失败: 用户未认证");

                // 返回明确的401错误，前端不会尝试刷新token
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
                headers.setCacheControl("no-cache, no-store, must-revalidate");

                return ResponseEntity
                        .status(HttpStatus.UNAUTHORIZED)
                        .headers(headers)
                        .body("{\"code\":401,\"message\":\"登录已过期，请重新登录后再尝试导出\",\"success\":false}");
            }

            log.info("授权用户: {}", authentication.getName());

            byte[] fileContent = orderService.exportOrders(orderNumber, supplierName, status, startDate, endDate);

            if (fileContent == null || fileContent.length == 0) {
                log.warn("导出订单数据为空");
                return ResponseEntity.status(HttpStatus.NO_CONTENT)
                        .contentType(MediaType.APPLICATION_JSON)
                        .body("{\"code\":204,\"message\":\"没有可导出的数据\",\"success\":false}");
            }

            log.info("成功生成导出文件，大小: {} 字节", fileContent.length);

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
            headers.setContentDispositionFormData("attachment", "orders_" + System.currentTimeMillis() + ".xlsx");
            // 添加缓存控制和下载属性
            headers.setCacheControl("no-cache, no-store, must-revalidate");
            headers.setPragma("no-cache");
            headers.setExpires(0);

            log.info("导出订单成功，返回Excel文件");

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(fileContent);
        } catch (Exception e) {
            log.error("导出订单失败: {}", e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .contentType(MediaType.APPLICATION_JSON)
                    .body("{\"code\":500,\"message\":\"导出订单失败: " + e.getMessage() + "\",\"success\":false}");
        }
    }

    @GetMapping("/{id}/related-documents")
    @Operation(summary = "获取订单关联单据", description = "获取与订单关联的收货单和发票信息")
    public Result<Object> getOrderRelatedDocuments(@Parameter(description = "订单ID") @PathVariable Long id) {
        try {
            log.info("获取订单关联单据, ID: {}", id);
            Object relatedDocs = orderService.getOrderRelatedDocuments(id);
            return Result.success(relatedDocs);
        } catch (Exception e) {
            log.error("获取订单关联单据失败, ID: {}", id, e);
            return Result.error("获取订单关联单据失败: " + e.getMessage());
        }
    }
} 